package aom.ju.ss.utils

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.provider.MediaStore
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import aom.ju.ss.R
import aom.ju.ss.lpInterface.ShowImgBack
import aom.ju.ss.lpInterface.TitleDialogInterface
import aom.ju.ss.utils.FileUtils.newPngFile
import aom.ju.ss.utils.FileUtils.saveBitmapFile
import aom.ju.ss.view.dialog.TitleDialog
import java.io.File
import java.io.IOException


/**
 * Created by Administrator on 2017/2/21 0021.
 */
class CameraUtils {
    private var activity: Activity? = null
    private var fragment: Fragment? = null
    private var file: File? = null

    constructor(activity: Activity) {
        this.activity = activity
    }

    private constructor(fragment: Fragment) {
        this.fragment = fragment
    }

    fun showPic(): CameraUtils {
        file = newPngFile()
        val intent = Intent(
            Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        )
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        if (fragment != null) {
            fragment!!.startActivityForResult(intent, IMAGE)
        } else {
            activity?.startActivityForResult(intent, IMAGE)
        }
        return this
    }


    private var back: ShowImgBack? = null
    private var type: Any? = null
    fun show(back: ShowImgBack?, type: Any?) {
        this.back = back
        this.type = type
        show()
    }

    fun showPic(back: ShowImgBack?, type: Any?) {
        this.back = back
        this.type = type
        showPic()
    }


    fun show(): CameraUtils {
        file = newPngFile()
        if (activity != null) {

            ActivityCompat.requestPermissions(
                activity!!,
                arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE),
                permissionCAMERA
            )
        } else if (fragment != null) {
            fragment!!.requestPermissions(
                arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE),
                permissionCAMERA
            )
        }
//        if (ActivityCompat.checkSelfPermission(
//                (if (activity != null) activity else if (fragment != null) fragment!!.context else BaseApplication.getInstance().applicationContext)!!,
//                Manifest.permission.CAMERA
//            ) != 0 ||
//            ActivityCompat.checkSelfPermission(
//                (if (activity != null) activity else if (fragment != null) fragment!!.context else BaseApplication.getInstance().applicationContext)!!,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE
//            ) != 0
//        ) {
//            ActivityCompat.requestPermissions(
//                (if (activity != null) activity else if (fragment != null) fragment!!.activity else null)!!,
//                arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE),
//                permissionCAMERA
//            )
//        } else {
//            showCamera()
//        }
        return this
    }

    private fun showCamera(): CameraUtils {

        file = newPngFile()
        val openCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) // 系统常量， 启动相机的关键
//        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
        val photoUri = FileProvider.getUriForFile(
            BaseApplication.getInstance(),
            BaseApplication.getInstance().packageName + ".fileprovider",
            file!!
        )

        if (fragment != null) {

            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
            fragment!!.startActivityForResult(
                openCameraIntent,
                RequestCamera
            ) // 参数常量为自定义的request code, 在取返回结果时有用
        } else {

            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
            activity!!.startActivityForResult(
                openCameraIntent,
                RequestCamera
            ) // 参数常量为自定义的request code, 在取返回结果时有用
        }

        return this
    }

    fun onPermissions(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        for (a in grantResults) {
            LogUtils.e("grantResults$a----------requestCode=$requestCode")
        }
        if (grantResults.isEmpty()) {
            return
        }
        when (requestCode) {
            1011 -> if (grantResults[0] == 0) {
                showCamera()
            } else {
                if (fragment != null) {
                    activity = fragment!!.requireActivity()
                }
                TitleDialog()
                    .show(activity, object : TitleDialogInterface {
                        override fun ok(view: View?, IsDetermine: Boolean) {

                            ActivityCompat.requestPermissions(
                                activity!!,
                                arrayOf(
                                    Manifest.permission.CAMERA,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                                ),
                                permissionCAMERA
                            )
                        }

                    })
                    .setConnect(BaseApplication.getInstance().getString(R.string.myxjqx))
                    .tvDetermine(BaseApplication.getInstance().getString(R.string.sz))
                    .tvCancel(BaseApplication.getInstance().getString(R.string.no))
            }
            else -> {
            }
        }
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): File? {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == IMAGE) {
                var bitmap: Bitmap? = null

                if (data?.data != null) {
                    bitmap = BitmapFactory.decodeStream(
                        BaseApplication.getInstance().contentResolver.openInputStream(data.data!!)
                    )
                }

                val files = saveBitmapFile(bitmap!!, file!!.absolutePath)
                if (back != null) {
                    back!!.getImgOk(files, type!!)
                }
                return files
            } else if (requestCode == RequestCamera) {

                val f = FileUtils.CPSCC(file!!.absolutePath)
//                    val bm = data.extras!!["data"] as Bitmap?
//                    val files = saveBitmapFile(bm!!, file!!.absolutePath)
                if (back != null) {
                    back!!.getImgOk(f!!, type!!)
                }
                return f
//                } else {
//                    null
//                }

            }
        }
        return null
    }


    companion object {
        private const val IMAGE = 1435
        private const val RequestCamera = 110
        private const val permissionCAMERA = 1011

        @JvmStatic
        fun isNew(activity: Activity): CameraUtils {
            return CameraUtils(activity)
        }

        @JvmStatic
        fun isNew(fragment: Fragment): CameraUtils {
            return CameraUtils(fragment)
        }

        /**
         * 获取图片的旋转角度
         *
         * @param path 图片绝对路径
         * @return 图片的旋转角度
         */
        fun getBitmapDegree(path: String): Int {
            var degree = 0
            try {
                // 从指定路径下读取图片，并获取其EXIF信息
                val exifInterface = ExifInterface(path)
                // 获取图片的旋转信息
                val orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL
                )
                when (orientation) {
                    ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90
                    ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180
                    ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return degree
        }

        /**
         * 将图片按照指定的角度进行旋转
         *
         * @param bitmap 需要旋转的图片
         * @param degree 指定的旋转角度
         * @return 旋转后的图片
         */
        fun rotateBitmapByDegree(bitmap: Bitmap, degree: Int): Bitmap {
            // 根据旋转角度，生成旋转矩阵
            val matrix = Matrix()
            matrix.postRotate(degree.toFloat())
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            //        if (!bitmap.isRecycled()) {
//            bitmap.recycle();
//        }
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
        }
    }
}